package com.ch.boundarycallbackdemo.retrofit

import com.ch.common.utils.LogUtils
import okhttp3.Interceptor
import okhttp3.Response
import okhttp3.ResponseBody
import okio.Buffer

/**
 * Author: chenhu
 * Time: 2021/8/31 10:49
 * Description do somethings
 */
class LoggingInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val timeStart = System.currentTimeMillis()
        val request = chain.request()
        val response = chain.proceed(request)
        val buffer = Buffer()
        request.body?.writeTo(buffer)
        val requestBodyStr = buffer.readUtf8()
        LogUtils.v("请求网址:${request.url},  请求参数:${requestBodyStr}")
        //TODO response.body?.string()这句话每次只能使用一次，所以要重新建一个newResponse用于作为返回数据
        val resultData = response.body?.string() ?: "response body null"
        val mediaType = response.body?.contentType()
        val newBody = ResponseBody.create(mediaType, resultData)
        val newResponse = response.newBuilder().body(newBody).build()
        val timeEnd = System.currentTimeMillis()
        val time = (timeEnd - timeStart).toString()
        LogUtils.v("返回结果用时:${time}毫秒，  返回数据:${resultData}")
        return newResponse
    }
}